package org.laokouyun.demo.discovery;

import io.grpc.NameResolver;
import io.grpc.NameResolverProvider;
import lombok.RequiredArgsConstructor;
import org.laokouyun.demo.ThreadUtils;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.event.EventListener;
import java.net.URI;

@RequiredArgsConstructor
public class DiscoveryNameResolverProvider extends NameResolverProvider {

    private final DiscoveryClient discoveryClient;

    private DiscoveryNameResolver discoveryNameResolver;

    @Override
    protected boolean isAvailable() {
        return true;
    }

    @Override
    protected int priority() {
        return 6;
    }

    @Override
    public NameResolver newNameResolver(URI uri, NameResolver.Args args) {
       return discoveryNameResolver = new DiscoveryNameResolver(uri.getHost(), discoveryClient, ThreadUtils.newVirtualTaskExecutor(), args);
    }

    @Override
    public String getDefaultScheme() {
        return "discovery";
    }

    @EventListener(HeartbeatEvent.class)
    public void onHeartbeatEvent(HeartbeatEvent event) {
        if (discoveryNameResolver != null) {
            discoveryNameResolver.refreshFromExternal();
        }
    }
}
